/*
 * @lc app=leetcode.cn id=1021 lang=javascript
 *
 * [1021] 删除最外层的括号
 */

// @lc code=start
/**
 * @param {string} S
 * @return {string}
 */
var removeOuterParentheses = function (S) {
  // 左右括号差值为0，就是一个外层括号
  let count = 0;
  let result = '';
  let start = 0;
  for (let i = 0; i < S.length; i++) {
    let char = S[i];
    if (char === '(') count++;
    else count--;
    if (count !== 0) continue;
    result += S.substring(start + 1, i);
    start = i + 1;
  }

  return result;
};
// @lc code=end
